package com.tdx.blog_nowcoder.controller;

import com.google.code.kaptcha.Producer;
import com.tdx.blog_nowcoder.constant.ActivateConstant;
import com.tdx.blog_nowcoder.constant.CommentReplyConstant;
import com.tdx.blog_nowcoder.entity.DiscussPort;
import com.tdx.blog_nowcoder.entity.User;
import com.tdx.blog_nowcoder.service.DiscussPortService;
import com.tdx.blog_nowcoder.service.LikeService;
import com.tdx.blog_nowcoder.service.UserService;
import com.tdx.blog_nowcoder.utils.Page;
import com.tdx.blog_nowcoder.utils.RandomUUID;
import com.tdx.blog_nowcoder.utils.RedisKeyUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.tdx.blog_nowcoder.constant.ActivateConstant.DEFAULT_EXPIRED_SECONDS;
import static com.tdx.blog_nowcoder.constant.ActivateConstant.REMEMBER_EXPIRED_SECONDS;


@Controller
public class HomeController {
    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private DiscussPortService discussPortService;

    @Autowired
    private LikeService likeService;

    @Autowired
    private Producer kapthproducer;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @RequestMapping(path = "/")
    public String root(){
        return "forward:/index";
    }


    @RequestMapping(path = "/index")
    public String index(Model model, Page page, @RequestParam(name = "orderMode",defaultValue = "0") int orderMode) {
        //分页功能
        page.setTotalPageNums(discussPortService.getTotalRows(0));
        page.setPath("/index?orderMode="+orderMode);
        // orderMode =0 表示最新排序，orderMode=1表示最热排序
        List<DiscussPort> portList = discussPortService.selectDiscussPosts(0, page.getOffset(), page.getPerPageSize(),orderMode);
        List<Map<String, Object>> port_user_Map = new ArrayList<>();
        if (portList != null) {
            for (DiscussPort port : portList) {
                Map<String, Object> map = new HashMap<>();
                map.put("post", port);
                User user = userService.selectUserById(port.getUserId());
                if (user != null) {
                    map.put("user", user);
                }

                // 帖子类型 点赞数量
                long discussport_count = likeService.findEntityLikeCount(CommentReplyConstant.ENTITY_TYPE_COMMENT,port.getId());
                map.put("discussport_count", discussport_count);
                port_user_Map.add(map);

            }
        }
        model.addAttribute("port_user_Map", port_user_Map);
        model.addAttribute("orderMode",orderMode);

        return "index2";
    }

    @RequestMapping(path = "/login", method = RequestMethod.GET)
    public String getloginPage() {
        return "site/login2";
    }

    @RequestMapping(path = "/login", method = RequestMethod.POST)
    public String login(String username, String password, String verifycode, boolean rememberme,
                        Model model,  @CookieValue("kaptchaOwner") String kaptchaOwner, HttpServletResponse response) {


        //获取之前放在session的验证码的值
//        String text = (String) session.getAttribute("img_code");
        String text = null;
        if (StringUtils.isNotBlank(kaptchaOwner)) {
            String redisKey = RedisKeyUtils.getKapthKey(kaptchaOwner);
            text = (String) redisTemplate.opsForValue().get(redisKey);
        }

        if (StringUtils.isBlank(text) || StringUtils.isBlank(verifycode) || !text.equalsIgnoreCase(verifycode)) {
            model.addAttribute("codeMsg", "验证码不正确!");
            return "site/login";
        }

        int expiredSeconds = rememberme ? REMEMBER_EXPIRED_SECONDS : DEFAULT_EXPIRED_SECONDS;
        Map<String, Object> map = userService.validLogin(username, password, expiredSeconds);
        if (map.containsKey("ticket")) {
            Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
            cookie.setPath(contextPath);
            cookie.setMaxAge(expiredSeconds);
            response.addCookie(cookie);
            return "redirect:/index";
        } else {
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            model.addAttribute("rememberme", rememberme);
            return "site/login";
        }
    }

    @RequestMapping(path = "/register", method = RequestMethod.GET)
    public String registerPage () {
        return "site/register";
    }

    @RequestMapping(path = "/register",method = RequestMethod.POST)
    public String postregister(Model model,User user){
        Map<String,Object> map = userService.registerUser(user);
        if(map==null||map.isEmpty()){
            model.addAttribute("msg", "注册成功,我们已经向您的邮箱发送了一封激活邮件,请尽快激活!");
            model.addAttribute("target", "/index");
            return "site/operate-result";
        }else {
//            System.out.println(map);
//            System.out.println(map.get("passwordMsg"));
//            System.out.println(user);
            //注册有错误消息提示
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            model.addAttribute("emailMsg", map.get("emailMsg"));

            return "site/register";
        }


    }

    @RequestMapping(path = "/logout", method = RequestMethod.GET)
    public String logout(@CookieValue("ticket") String ticket) {
        userService.logout(ticket); // 注销功能
        SecurityContextHolder.clearContext();
        return "redirect:/login";
    }

    @RequestMapping(path = "/getImgCode",method = RequestMethod.GET)
    public void getImgCode(HttpServletResponse response){
        String text = kapthproducer.createText();
        BufferedImage image = kapthproducer.createImage(text);
        // 将验证码存入session
        //session.setAttribute("img_code",text);

        //随机生成拥有者
        String kapthOwner = RandomUUID.getUUID();

        //存在cookie中,再添加到response
        Cookie cookie = new Cookie("kaptchaOwner",kapthOwner);
        cookie.setMaxAge(120);
        cookie.setPath(contextPath);
        response.addCookie(cookie);

        //存入redis
        String kapthRedisKey = RedisKeyUtils.getKapthKey(kapthOwner);
        redisTemplate.opsForValue().set(kapthRedisKey,text,120, TimeUnit.SECONDS);

        response.setContentType("image/png");

        try {
            OutputStream os = response.getOutputStream();
            ImageIO.write(image,"png",os);
        } catch (IOException e) {
            logger.error("响应验证码失败----"+e.getMessage());
        }
    }


    // 激活邮箱 http://localhost:8081/tdx/activation/151/4797cc9df50b4d88878894d420286ad4

    @RequestMapping(path = "/activation/{userID}/{code}",method = RequestMethod.GET)
    public String activateUser(Model model, @PathVariable("userID") int userID, @PathVariable("code") String code){
        int result = userService.activateUser(userID, code);
        if (result == ActivateConstant.ACTIVATION_SUCCESS) {
            model.addAttribute("msg", "激活成功,您的账号已经可以正常使用了!");
            model.addAttribute("target", "/login");
        } else if (result == ActivateConstant.ACTIVATION_REPEAT) {
            model.addAttribute("msg", "无效操作,该账号已经激活过了!");
            model.addAttribute("target", "/index");
        } else {
            model.addAttribute("msg", "激活失败,您提供的激活码不正确!");
            model.addAttribute("target", "/index");
        }
        return "site/operate-result";

    }


    //服务器异常处理返回页面
    @RequestMapping(path = "/error",method = RequestMethod.GET)
    public String error(){
        return "/error/500";
    }

    @RequestMapping(path = "/denied", method = RequestMethod.GET)
    public String getDeniedPage() {
        return "/error/404";
    }
}
